<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import { getLocalIcons, getSystemIcons } from '@/utils/icon';
import { ElMessage, ElMessageBox } from 'element-plus';

defineOptions({ name: 'IconPage' });

// 图标类型定义
interface IconItem {
  id: number;
  name: string;
  type?: 'local' | 'system'; // 图标类型：本地图标或系统图标
}

// 本地图标列表 (local-icon)
const localIcons = ref<IconItem[]>([]);
// 系统图标列表 (svg-icon)
const systemIcons = ref<IconItem[]>([]);
// 表格加载状态
const loading = ref(false);
// 当前正在编辑的图标
const currentIcon = ref<IconItem | null>(null);
// 对话框可见性
const dialogVisible = ref(false);
// 对话框类型：edit (修改) 或 add (新增)
const dialogType = ref<'edit' | 'add'>('edit');
// 新图标名称
const newIconName = ref('');
// 上传文件
const uploadFile = ref<File | null>(null);

// 对话框标题
const dialogTitle = computed(() => {
  if (dialogType.value === 'add') {
    return '新增图标';
  }
  return currentIcon.value?.type === 'local' ? '修改本地图标' : '修改系统图标';
});

// 初始化
onMounted(() => {
  loadIcons();
});

// 加载图标列表
function loadIcons() {
  loading.value = true;
  try {
    // 获取本地图标 (local-icon)
    const localIconList = getLocalIcons();
    localIcons.value = localIconList.map((name, index) => ({
      id: index + 1,
      name,
      type: 'local'
    }));
    
    // 获取系统图标 (svg-icon)
    const systemIconList = getSystemIcons();
    systemIcons.value = systemIconList.map((name, index) => ({
      id: index + 1,
      name,
      type: 'system'
    }));
    
    console.log('本地图标:', localIcons.value);
    console.log('系统图标:', systemIcons.value);
  } catch (error) {
    console.error('加载图标失败:', error);
  } finally {
    loading.value = false;
  }
}

// 打开新增图标对话框
function handleAdd() {
  dialogType.value = 'add';
  newIconName.value = '';
  uploadFile.value = null;
  dialogVisible.value = true;
}

// 编辑图标
function handleEdit(row: IconItem) {
  dialogType.value = 'edit';
  currentIcon.value = row;
  newIconName.value = row.name;
  dialogVisible.value = true;
}

// 删除图标
function handleDelete(row: IconItem) {
  if (row.type !== 'local') {
    ElMessage.warning('只能删除本地图标');
    return;
  }
  
  ElMessageBox.confirm(`确定要删除图标 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用后端API删除图标文件
    // 模拟删除成功
    const index = localIcons.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      localIcons.value.splice(index, 1);
      ElMessage.success(`图标 "${row.name}" 删除成功`);
    }
  }).catch(() => {
    // 取消删除
  });
}

// 保存图标修改
function handleSave() {
  if (dialogType.value === 'add') {
    if (!newIconName.value || !uploadFile.value) {
      ElMessage.warning('图标名称和文件不能为空');
      return;
    }
    
    // 检查文件类型
    if (uploadFile.value.type !== 'image/svg+xml') {
      ElMessage.warning('只能上传SVG格式的图标');
      return;
    }
    
    // 这里应该调用后端API上传图标文件
    // 模拟上传成功
    const newId = localIcons.value.length > 0 
      ? Math.max(...localIcons.value.map(icon => icon.id)) + 1 
      : 1;
      
    localIcons.value.push({
      id: newId,
      name: newIconName.value,
      type: 'local'
    });
    
    ElMessage.success(`图标 "${newIconName.value}" 添加成功`);
    dialogVisible.value = false;
    return;
  }
  
  if (!newIconName.value) {
    ElMessage.warning('图标名称不能为空');
    return;
  }
  
  if (currentIcon.value) {
    // 这里应该调用后端API修改图标名称
    // 模拟修改成功
    ElMessage.success(`图标 "${currentIcon.value.name}" 修改为 "${newIconName.value}" 成功`);
    
    // 更新本地数据
    if (currentIcon.value.type === 'local') {
      const icon = localIcons.value.find(item => item.id === currentIcon.value?.id);
      if (icon) {
        icon.name = newIconName.value;
      }
    } else {
      const icon = systemIcons.value.find(item => item.id === currentIcon.value?.id);
      if (icon) {
        icon.name = newIconName.value;
      }
    }
    
    dialogVisible.value = false;
  }
}

// 文件选择改变
function handleFileChange(e: Event) {
  const target = e.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    uploadFile.value = target.files[0];
  }
}
</script>

<template>
  <div class="h-full page-container">
    <!-- 本地图标表格 -->
    <el-card class="mb-16px">
      <template #header>
        <div class="flex justify-between items-center">
          <span>本地图标管理</span>
          <el-button type="primary" @click="handleAdd">新增图标</el-button>
        </div>
      </template>
      
      <el-table 
        :data="localIcons" 
        border 
        v-loading="loading" 
        row-key="id"
        height="250px"
        class="icon-table"
      >
        <el-table-column label="ID" prop="id" width="80" sortable />
        <el-table-column label="图标名称" prop="name" min-width="120" />
        <el-table-column label="图标预览" width="200" align="center">
          <template #default="{ row }">
            <div class="flex-center">
              <i>
                <svg-icon :local-icon="row.name" class="text-24px" />
              </i>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              修改
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="mt-16px">
        <p class="text-sm text-gray-500">图标位置：src/assets/local-icon/*.svg</p>
      </div>
    </el-card>
    
    <!-- 系统图标表格 -->
    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span>系统图标表格</span>
        </div>
      </template>
      
      <el-table 
        :data="systemIcons" 
        border 
        v-loading="loading" 
        row-key="id"
        height="250px"
        class="icon-table"
      >
        <el-table-column label="ID" prop="id" width="80" sortable />
        <el-table-column label="图标名称" prop="name" min-width="120" />
        <el-table-column label="使用场景" min-width="120">
          <template #default>
            <span class="text-gray-400">系统组件</span>
          </template>
        </el-table-column>
        <el-table-column label="图标预览" width="200" align="center">
          <template #default="{ row }">
            <div class="flex-center">
              <i>
                <svg-icon :local-icon="row.name" class="text-24px" />
              </i>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="mt-16px">
        <p class="text-sm text-gray-500">图标位置：src/assets/svg-icon/*.svg</p>
      </div>
    </el-card>
    
    <!-- 公共对话框：新增/修改图标 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="450px">
      <el-form label-position="top">
        <!-- 新增图标时显示文件上传 -->
        <el-form-item v-if="dialogType === 'add'" label="上传SVG图标">
          <input 
            type="file" 
            accept=".svg" 
            @change="handleFileChange"
            class="file-input"
          />
          <div class="text-sm text-gray-400 mt-5px">
            只能上传SVG格式图标，且大小不超过100KB
          </div>
        </el-form-item>
        
        <el-form-item label="图标名称">
          <el-input v-model="newIconName" placeholder="请输入图标名称" />
          <div class="text-sm text-gray-400 mt-5px">
            图标名称不能包含特殊字符，建议使用英文或英文+数字
          </div>
        </el-form-item>
        
        <!-- 显示当前图标预览 -->
        <el-form-item v-if="dialogType === 'edit' && currentIcon" label="当前图标">
          <div class="flex-y-center">
            <svg-icon :local-icon="currentIcon.name" class="text-32px mr-10px" />
            <span>{{ currentIcon.name }}</span>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="flex justify-end gap-10px">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page-container {
  overflow-y: auto;
  padding-bottom: 16px;
}

.icon-table {
  width: 100%;
}

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.flex-y-center {
  display: flex;
  align-items: center;
}

.file-input {
  width: 100%;
  padding: 10px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}

.file-input:hover {
  border-color: #409eff;
}

.mr-10px {
  margin-right: 10px;
}

.mt-5px {
  margin-top: 5px;
}
</style>
